package com.vhly.apb;

import android.database.Cursor;
import com.vhly.remoteapi.parser.XMLParser;
import com.vhly.remoteapi.yahoo.contact.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 10-12-24
 * Time: 13:45
 */
public class ContactSyncStore {

    private Hashtable<String, ContactObject> store;

    private static ContactSyncStore outInstance;

    public static ContactSyncStore getInstance() {
        if (outInstance == null) {
            outInstance = new ContactSyncStore();
        }
        return outInstance;
    }

    /**
     * Current Client's rev (sync support)
     */
    private String clientRev;

    private ContactCursor contacts;

    private ContactSyncStore() {
        store = new Hashtable<String, ContactObject>();
        clientRev = "0";
    }

    public Cursor getContacts(){
        ContactCursor ret = null;
        if(store != null && store.size() > 0){
            Vector<ContactObject> cos = new Vector<ContactObject>(store.size());
            Collection<ContactObject> vs = store.values();
            cos.addAll(vs);
            ret = new ContactCursor(cos);
        }
        return ret;
    }

    public Vector<ContactObject> parseSync(String xml) {
        System.out.println("xml = " + xml);
        Vector<ContactObject> ret = null;
        if (xml != null) {
            try {
                Document doc = XMLParser.parse(xml);
                if (doc != null) {
                    Element root = doc.getDocumentElement();
                    clientRev = root.getAttribute("yahoo:rev");
                    System.out.println("rev = " + clientRev);
                    NodeList contacts = root.getElementsByTagName("contacts");
                    if (contacts != null) {
                        int len = contacts.getLength();
                        ret = new Vector<ContactObject>();
                        Contact ct;
                        for (int i = 0; i < len; i++) {
                            ct = new Contact();
                            ct.parse((Element) contacts.item(i));
                            ret.add(ct);
                        }
                    }
                }
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    public String getClientRev() {
        return clientRev;
    }

    public void setClientRev(String clientRev) {
        this.clientRev = clientRev;
    }

    /**
     * Update Contacts with cos
     * @param cos Vector&lt;ContactObject&gt; Sync from server
     * @return Updated count
     */
    public int updateStore(Vector<ContactObject> cos) {
        int ret = 0;

        if (cos != null) {
            int size = cos.size();
            ContactObject co;
            String skey = null;
            for (int i = 0; i < size; i++) {
                co = cos.get(i);
                if (co instanceof Contact) {
                    skey = "cont_" + co.id;
                } else if (co instanceof Category) {
                    skey = "cate_" + co.id;
                }
                if (skey != null) {
                    if (store.containsKey(skey)) {
                        if (co.status == Status.REMOVE) {
                            store.remove(skey);
                            ret++;
                        } else if (co.status == Status.UPDATE) {
                            ContactObject coold = store.get(skey);
                            coold.updated = co.updated;
                            if (co instanceof Contact) {
                                Contact ct = (Contact) co;
                                Contact ctold = (Contact) coold;
                                Vector<Field> nfs = ct.fields;
                                Vector<Field> ofs = ctold.fields;
                                for (Field fd : nfs) {
                                    String fid = fd.id;
                                    if (fd.status == Status.ADD) {
                                        ofs.add(fd);
                                        ret++;
                                    } else {
                                        for(Field fd1 : ofs){
                                            if(fd1.id.equals(fid)){
                                                // TODO Update or remove
                                                if(fd.status == Status.REMOVE){
                                                    ofs.remove(fd1);
                                                    ret++;
                                                }else if(fd.status == Status.UPDATE){
                                                    fd1.nickname = fd.nickname;
                                                    fd1.title = fd.title;
                                                    fd1.type = fd.type;
                                                    fd1.value = fd.value;
                                                    ret++;
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    } else {
                        if (co.status == Status.ADD) {
                            store.put(skey, co);
                            ret++;
                        }
                    }
                }
            }
        }
        return ret;
    }
}
